package com.ictech.print.utils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import com.ictech.print.event.JsEvent;

import de.greenrobot.event.EventBus;

public class HttpUtils {

	public static HttpUtils instance = null;
	
	private OkHttpClient client = null;
	
	private HttpUtils() {
		client = new OkHttpClient.Builder()
					.connectTimeout(10, TimeUnit.SECONDS)
					.readTimeout(10, TimeUnit.SECONDS)
					.build();
	}
	
	public static HttpUtils getInstance() {
		if (instance == null) {
			synchronized (HttpUtils.class) {
				if (instance == null) {
					instance = new HttpUtils();
				}
			}
		}
		return instance;
	}
	
	public String get(String url) {
		String result = "";
        try {
        	Request request = new Request.Builder().url(url).get().build();
            Call call = client.newCall(request);
            Response response = call.execute();
            result = response.body().string();
        } catch (IOException e) {
        	result = e.getMessage();
        }
        return result;
	}
	
	public void asynGet(String url, final String callback, final String callbackParam) {
		try {
        	Request request = new Request.Builder().url(url).get().build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {

				@Override
				public void onFailure(Call arg0, IOException e) {
					String result = e.getMessage();
					JsEvent jsEvent = new JsEvent();
					if ("checkIsConnectToMainCb".equals(callback)) {
						jsEvent.setJs("checkIsConnectToMainCb('0')");
					} else {
						jsEvent.setJs(callback + "('0', '" + result + "', '" + callbackParam + "')");
					}
					EventBus.getDefault().post(jsEvent);
				}

				@Override
				public void onResponse(Call arg0, Response response) throws IOException {
					String result = response.body().string();
					JsEvent jsEvent = new JsEvent();
					if ("checkIsConnectToMainCb".equals(callback)) {
						jsEvent.setJs("checkIsConnectToMainCb('1')");
					} else {
						jsEvent.setJs(callback + "('1', '" + result + "', '" + callbackParam + "')");
					}
					EventBus.getDefault().post(jsEvent);
				}
            	
            });
        } catch (Exception e) {
        	String result = e.getMessage();
        	JsEvent jsEvent = new JsEvent();
        	if ("checkIsConnectToMainCb".equals(callback)) {
				jsEvent.setJs("checkIsConnectToMainCb('0')");
			} else {
				jsEvent.setJs(callback + "('0', '" + result + "', '" + callbackParam + "')");
			}
			EventBus.getDefault().post(jsEvent);
        }
	}
	
}
